<template>
    <basic-container>
        <p>
            <vxe-button @click="getTreeExpansionEvent">获取已展开</vxe-button>
            <vxe-button @click="expandAllEvent">展开所有</vxe-button>
            <vxe-button @click="closeExpandEvent">关闭所有</vxe-button>

            <vxe-button>
                <template #default>校验操作</template>
                <template #dropdowns>
                    <vxe-button type="text" @click="validEvent">快速校验</vxe-button>
                    <vxe-button type="text" @click="fullValidEvent">完整快速校验</vxe-button>
                    <vxe-button type="text" @click="selectValidEvent">选中行校验</vxe-button>
                </template>
            </vxe-button>

        </p>

        <vxe-table
                show-overflow
                border="full"
                ref="xTreeRef"
                height="400"
                keep-source
                :loading="loading"
                :scroll-y="{gt: 10}"
                :column-config="{resizable: true}"
                :tree-config="{transform: true, rowField: 'id', parentField: 'parentId'}"
                :data="tableData"
                :edit-rules="validRules"
                :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
                @toggle-tree-expand="toggleTreeExpand">
            <vxe-column width="60" align="center">
                <template #default>
                  <span class="drag-btn">
                    <i class="vxe-icon-edit"></i>
                  </span>
                </template>
            </vxe-column>
            <vxe-column field="name" title="名称" width="300" tree-node sortable
                        :edit-render="{autoselect: true, name: 'EditDownTextarea', props: {maxlength: 50, rows: 5, showWordCount: true}}">
            </vxe-column>
            <vxe-column field="size" title="尺寸"></vxe-column>
            <vxe-column field="type" title="类型"></vxe-column>
            <vxe-column field="date" title="日期" :edit-render="{}">
                <template #edit="scope">
                    <vxe-input v-model="scope.row.date" type="date" transfer placeholder="请选择日期"
                               @change="$refs.xTreeRef.updateStatus(scope)"></vxe-input>
                </template>
            </vxe-column>
            <vxe-column title="操作" width="20%">
                <template #default="{ row }">
                    <template v-if="isActiveStatus(row)">
                        <vxe-button @click="saveRowEvent(row)">保存</vxe-button>
                        <vxe-button @click="cancelRowEvent(row)">取消</vxe-button>
                    </template>
                    <template v-else>
                        <vxe-button @click="editRowEvent(row)">编辑</vxe-button>
                    </template>
                </template>
            </vxe-column>
        </vxe-table>
    </basic-container>
</template>

<script>
    import Sortable from 'sortablejs'
    import VXETable from 'vxe-table'

    export default {
        data() {
            return {
                loading: false,
                sortable1: null,
                // 数据列表
                tableData: [
                    {id: 10000, parentId: null, name: 'Test1', type: 'mp3', size: 1024, date: '2020-08-01'},
                    {id: 10050, parentId: null, name: 'Test2', type: 'mp4', size: 0, date: '2021-04-01'},
                    {id: 24300, parentId: 10050, name: 'Test3', type: 'avi', size: 1024, date: '2020-03-01'},
                    {id: 20045, parentId: 24300, name: 'Test4', type: 'html', size: 600, date: '2021-04-01'},
                    {id: 10053, parentId: 24300, name: 'Test5', type: 'avi', size: 0, date: '2021-04-01'},
                    {id: 24330, parentId: 10053, name: 'Test6', type: 'txt', size: 25, date: '2021-10-01'},
                    {id: 21011, parentId: 10053, name: 'Test7', type: 'pdf', size: 512, date: '2020-01-01'},
                    {id: 22200, parentId: 10053, name: 'Test8', type: 'js', size: 1024, date: '2021-06-01'},
                    {id: 23666, parentId: null, name: 'Test9', type: 'xlsx', size: 2048, date: '2020-11-01'},
                    {id: 23677, parentId: 23666, name: 'Test10', type: 'js', size: 1024, date: '2021-06-01'},
                    {id: 23671, parentId: 23677, name: 'Test11', type: 'js', size: 1024, date: '2021-06-01'},
                    {id: 23672, parentId: 23677, name: 'Test12', type: 'js', size: 1024, date: '2021-06-01'},
                    {id: 23688, parentId: 23666, name: 'Test13', type: 'js', size: 1024, date: '2021-06-01'},
                    {id: 23681, parentId: 23688, name: 'Test14', type: 'js', size: 1024, date: '2021-06-01'},
                    {id: 23682, parentId: 23688, name: 'Test15', type: 'js', size: 1024, date: '2021-06-01'},
                    {id: 24555, parentId: null, name: 'Test16', type: 'avi', size: 224, date: '2020-10-01'},
                    {id: 24566, parentId: 24555, name: 'Test17', type: 'js', size: 1024, date: '2021-06-01'},
                    {id: 24577, parentId: 24555, name: 'Test18', type: 'js', size: 1024, date: '2021-06-01'}
                ],
                // 校验
                validRules: {
                    name: [
                        {required: true, message: '请填写名称', trigger: "change"},
                        {min: 3, max: 50, message: '名称长度在 3 到 50 个字符', trigger: "change"}
                    ],
                    date: [
                        // {required: true, message: '日期必须填写', trigger: "change"}
                        // {
                        //     validator: ({cellValue, rule, rules, row, rowIndex, column, columnIndex}) => {
                        //         return new Promise((resolve, reject) => {
                        //             reject(new Error("请填写dfkjfd\nxxxx"))
                        //         })
                        //     }
                        // }
                    ]
                }
            };
        },
        created() {

            // VXETable.interceptor.add('event.clearEdit', (params, event) => {
            //     console.log(params);
            //     // 比如点击了某个组件的弹出层面板之后，此时被激活单元格不应该被自动关闭，通过返回 false 可以阻止默认的行为。
            //     if (event.target.className.indexOf('other-popper') > -1) {
            //         return false
            //     }
            // })
        },
        mounted() {
            const _this = this;
            _this.loading = true
            setTimeout(() => {
                _this.loading = false
                for (let i = 0; i < 300; i++) {
                    _this.tableData.push({
                        id: i,
                        parentId: i % 4 || i % 2 ? i - 1 : null,
                        name: 'Test' + (i + 1 + 18),
                        type: 'js',
                        size: 1024,
                        date: '2021-06-01'
                    })
                }
            }, 3000)
            this.$nextTick(() => {
                this.rowDrop()
            })

        },
        methods: {
            toggleTreeExpand(params) {
                const $table = this.$refs.xTreeRef
                if ($table) {
                    const {row, expanded} = params;
                    console.log('节点展开事件', expanded, '获取父节点：', $table.getParentRow(row))
                }
            },
            getTreeExpansionEvent() {
                const $table = this.$refs.xTreeRef;
                if ($table) {
                    const treeExpandRecords = $table.getTreeExpandRecords()
                    VXETable.modal.alert(treeExpandRecords.length)
                }
            },
            expandAllEvent() {
                const $table = this.$refs.xTreeRef;
                if ($table) {
                    $table.setAllTreeExpand(true)
                }
            },
            closeExpandEvent() {
                const $table = this.$refs.xTreeRef;
                if ($table) {
                    $table.clearTreeExpand()
                }
            },
            validEvent() {
                const $table = this.$refs.xTreeRef
                $table.validate(true).then(errMap => {
                    console.log(errMap);
                    if (errMap) {
                        VXETable.modal.message({status: 'error', content: '校验不通过！'})
                    } else {
                        VXETable.modal.message({status: 'success', content: '校验成功！'})
                    }
                });
            },


            getRowParentExpand(data) {
                let rows = [];
                const $table = this.$refs.xTreeRef;
                if (data) {
                    if (!$table.isTreeExpandByRow(data)) {
                        rows.unshift(data);
                    }
                    const key = data._X_ROW_KEY;
                    const parent = $table.getParentRow(key);
                    if (parent) {
                        const lastRow = this.getRowParentExpand(parent);
                        if (lastRow && lastRow.length) {
                            rows.unshift(...lastRow)
                        }
                    }
                }
                return rows
            },
            addErrorRow(key) {
                const $table = this.$refs.xTreeRef;
                const trEl = $table.$el.querySelector(`tr[rowid=${key}]`);
                if (trEl) {
                    trEl.classList.add("error")
                }
            },
            fullValidEvent() {
                const $table = this.$refs.xTreeRef

                $table.fullValidate(true).then(errMap => {
                    if (errMap) {
                        // 查找错误的行key,并去重复
                        let rowKeys = [];
                        Object.values(errMap).forEach((errList) => {
                            errList.forEach(params => {
                                const key = params.row._X_ROW_KEY;
                                if (!rowKeys.includes(key)) {
                                    rowKeys.push(key)
                                }
                            })
                        });
                        // 设置错误行显示，
                        rowKeys.forEach(key => {
                            // 如果有父级，且父级处于折叠，则先展开再设置
                            const parent = $table.getParentRow(key);
                            if (parent) {
                                const expandRows = this.getRowParentExpand(parent);
                                if (expandRows && expandRows.length) {
                                    $table.setTreeExpand(expandRows, true).then(()=> {
                                        this.addErrorRow(key)
                                    })
                                    return;
                                }
                            }
                            this.addErrorRow(key)
                        });
                        // 移除错误
                        setTimeout(() => {
                            const trEls = $table.$el.querySelectorAll(".error");
                            trEls.forEach(el => {
                                el.classList.remove("error")
                            })
                        }, 3000)
                        // VXETable.modal.message({status: 'error', content: '校验失败！'})
                    } else {

                        VXETable.modal.message({status: 'success', content: '校验成功！'})
                    }
                });
            },
            selectValidEvent() {
                const $table = this.$refs.xTreeRef;
                const selectRecords = $table.getCheckboxRecords()
                if (selectRecords.length > 0) {
                    $table.validate(selectRecords, errMap => {
                        if (errMap) {
                            VXETable.modal.message({status: 'error', content: '校验不通过！'})
                        } else {
                            VXETable.modal.message({status: 'success', content: '校验成功！'})
                        }
                    });

                } else {
                    VXETable.modal.message({status: 'warning', content: '未选中数据！'})
                }
            },
            /**
             * 拖动
             */
            rowDrop() {
                const $table = this.$refs.xTreeRef
                this.sortable1 = Sortable.create($table.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
                    handle: '.drag-btn',
                    fallbackClass: "sortable-fallback",  // 当使用forceFallback的时候，被复制的dom的css类名
                    fallbackOnBody: true,  // 将cloned DOM 元素挂到body元素上。
                    fallbackTolerance: 0,
                    // 元素被选中
                    onChoose: function (/**Event*/evt) {
                        // evt.oldIndex;  // element index within parent
                        $table.getTableData();
                    },
                    onMove: function (/**Event*/evt, /**Event*/originalEvent) {
                        // Example: https://jsbin.com/nawahef/edit?js,output
                        evt.dragged; // dragged HTMLElement
                        evt.draggedRect; // DOMRect {left, top, right, bottom}
                        evt.related; // HTMLElement on which have guided
                        evt.relatedRect; // DOMRect
                        evt.willInsertAfter; // Boolean that is true if Sortable will insert drag element after target by default
                        originalEvent.clientY; // mouse position
                        // return false; — for cancel
                        // return -1; — insert before target
                        // return 1; — insert after target
                    },
                    onEnd: (sortableEvent) => {
                        const newIndex = sortableEvent.newIndex;
                        const oldIndex = sortableEvent.oldIndex;
                        const currRow = this.tableData.splice(oldIndex, 1)[0];
                        this.tableData.splice(newIndex, 0, currRow)
                    }
                })
            },
            isActiveStatus(row) {
                const $table = this.$refs.xTreeRef
                if ($table) {
                    return $table.isEditByRow(row)
                }
            },
            editRowEvent(row) {
                const $table = this.$refs.xTreeRef;
                if ($table) {
                    // 获取正在编辑项
                    let editRow = $table.getEditRecord();
                    if (editRow) {
                        // 有编辑项，就校验编辑项，
                        $table.validate(editRow.row, errMap => {
                            if (errMap) {
                                VXETable.modal.message({status: 'error', content: '校验不通过！'})
                            } else {
                                // 其他处理
                                VXETable.modal.message({status: 'success', content: '校验成功！'})
                                $table.setEditRow(row)
                            }
                        });
                    } else {
                        // 没有正在编辑项，就打开编辑
                        $table.setEditRow(row)
                    }
                }
            },
            saveRowEvent(row) {
                const $table = this.$refs.xTreeRef
                if ($table) {
                    $table.validate(row, errMap => {
                        if (errMap) {
                            VXETable.modal.message({status: 'error', message: '校验不通过！'})
                        } else {
                            $table.clearEdit().then(() => {
                                this.loading = true
                                setTimeout(() => {
                                    this.loading = false
                                    VXETable.modal.message({content: `保存成功！name=${row.name}`, status: 'success'})
                                }, 300)
                            })
                        }
                    });

                }
            },

            cancelRowEvent(row) {
                const $table = this.$refs.xTreeRef
                if ($table) {
                    $table.clearEdit().then(() => {
                        // 还原行数据
                        $table.revertData(row)
                    })
                }
            },
            // editClosed({row, rowIndex, $rowIndex, column, columnIndex, $columnIndex}) {
            editClosed({row, column}) {
                // const $table = this.$refs.xTreeRef;
                // this.loading = true
                // setTimeout(() => {
                //     this.loading = false
                //     $table.setEditCell(row, column.field);
                //     // $table.reloadRow(row, null, column.field);
                //     // VXETable.modal.message({content: `保存成功！name=${row.name}`, status: 'success'})
                // }, 3000)
            }
        },
        unmounted() {
            if (this.sortable1) {
                this.sortable1.destroy()
            }
        }
    };
</script>

<style>
    @keyframes blink {
        0% {
            opacity: 1;
        }
        50% {
            opacity: 0;
        }
        100% {
            opacity: 1;
        }
    }

    .error {
        animation: blink 3s linear infinite;
        background: red;
    }
</style>
